package com.pfsoft.codehelper.controller;

import cn.hutool.core.util.PageUtil;
import com.pfsoft.codehelper.common.exception.BadRequestException;
import com.pfsoft.codehelper.common.query.TableQuery;
import com.pfsoft.codehelper.common.response.BaseResponse;
import com.pfsoft.codehelper.domain.GenConfig;
import com.pfsoft.codehelper.domain.vo.ColumnInfo;
import com.pfsoft.codehelper.domain.vo.TableInfo;
import com.pfsoft.codehelper.service.GenConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class GeneratorController {

    @Autowired
    private com.pfsoft.service.GeneratorService generatorService;

    @Autowired
    private GenConfigService genConfigService;

    @Value("${generator.enabled}")
    private Boolean generatorEnabled;

    /**
     * 查询数据库元数据
     * @return
     */
    @PostMapping(value = "/api/generator/tables")
    public @ResponseBody ResponseEntity<BaseResponse<Page<TableInfo>>> getTables(@RequestBody TableQuery tableQuery){
        BaseResponse<Page<TableInfo>> baseResponse = new BaseResponse<>();
        Page<TableInfo> all = generatorService.getTables(tableQuery);
        baseResponse.setCode(200);
        baseResponse.setMessage("success");
        baseResponse.setData(all);
        return new ResponseEntity<>(baseResponse, HttpStatus.OK);
    }

    /**
     * 查询表内元数据
     * @param tableName
     * @return
     */
    @PostMapping(value = "/api/generator/columns")
    public @ResponseBody ResponseEntity<BaseResponse<List<ColumnInfo>>>   getColumns(String tableName){
        BaseResponse<List<ColumnInfo>> baseResponse=new BaseResponse<>();
        baseResponse.setCode(200);
        baseResponse.setMessage("success");
        baseResponse.setData(generatorService.getColumns(tableName));
        return new ResponseEntity<>(baseResponse,HttpStatus.OK);
    }

    /**
     * 生成代码
     * @return
     */
    @PostMapping(value = "/api/generator")
    public ResponseEntity generator(@RequestBody List<ColumnInfo> columnInfos, @RequestParam String tableName){
        if(!generatorEnabled){
            throw new BadRequestException("此环境不允许生成代码！");
        }
        GenConfig genConfig1 = genConfigService.find();
        //获取列信息
        generatorService.generator(columnInfos,genConfig1,tableName);
        return new ResponseEntity(HttpStatus.OK);
    }



    @GetMapping("/ctrl/generator")
    public String getConfigIndex() {
        return "/ctrl/generator";
    }
}
